import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created with IntelliJ IDEA.
 * Description:阻塞队列的实现
 * User: 邓大帅
 * Date: 2024-01-25
 * Time: 15:30
 */
class MyBlockingQueue {
    private int[] items = new int[10];
    volatile private int front;
    volatile private int rear;
    volatile private int size;
//    入队列
    synchronized public void put(int value) throws InterruptedException {
        while (size == items.length) {
//            队列满了，插入失败,阻塞等待
//            return;
            this.wait();
        }
        items[rear] = value;
        rear++;
        if (rear == items.length) {
            rear = 0;
        }
        size++;
        this.notify();
    }
//    出队列
    synchronized public Integer take() throws InterruptedException {
        while (size == 0) {
//            return null;
            this.wait();
        }
        int value = items[front];
        front++;
        if (front == items.length) {
            front = 0;
        }
        size--;
        this.notify();
        return value;
    }
}
public class ThreadDemo4 {
    public static void main(String[] args) {
        MyBlockingQueue blockingQueue = new MyBlockingQueue();
//        消费者
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    int value = blockingQueue.take();
                    System.out.println("消费:" + value);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
//        生产者
        Thread thread1 = new Thread(() -> {
            int value = 0;
            while (true) {
                try {
                    System.out.println("生产:" + value);
                    blockingQueue.put(value);
                    value++;
//                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        thread1.start();

    }
}
